<script>
(window.google && window.google.maps) || document.write('<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"><\/script>')
</script>

{$id = rand()}

<style type="text/css">
	#map_canvas_{$id} {
		width: {$width|default:'400'}px; 
		height: {$height|default:'400'}px;
	}
	#map_canvas_{$id} img {
		max-width: none;
	}
</style>

<div id="map_canvas_{$id}"></div>

<script>
	var map_{$id};
	var geocoder_{$id} = new google.maps.Geocoder();
	var marker_{$id};

	function initialize_{$id}() {

		var latlng = new google.maps.LatLng({$lat|default:'0'}, {$lng|default:'0'});

	    var mapOptions = {
	      zoom: {$zoom|default:'15'},
	      center: latlng,
	      mapTypeId: google.maps.MapTypeId.{$maptype|default:'roadmap'|upper}
	    };

	    map_{$id} = new google.maps.Map(document.getElementById('map_canvas_{$id}'), mapOptions);

		marker_{$id} = new google.maps.Marker({
		  	map: map_{$id},
		  	position: latlng,
		    draggable: true
		});


		{assign var=arrBinding value=","|explode:$binding}

		{foreach $arrBinding as $elementBinding}
			{assign var=bind value="."|explode:$elementBinding}
			jQuery("{$bind[0]}").on("{$bind[1]}", setLatLng_{$id});
		{/foreach}


	    google.maps.event.addListener(marker_{$id}, 'dragend', function() {
	      	var point = marker_{$id}.getPosition();
			{$latHidden}.val(point.lat());
			{$lngHidden}.val(point.lng());
	      	map_{$id}.setCenter(point);
	    });

	} // initialize_{$id}

	google.maps.event.addDomListener(window, 'load', initialize_{$id});


	function setLatLng_{$id}(event) {
		var address;
		var city;
		var state;
		var country;
		try {address = eval("{$address}");} catch(err) {address = "{$address}"};
		try {city    = eval("{$city}");   } catch(err) {city    = "{$city}"};
		try {state   = eval("{$state}");  } catch(err) {state   = "{$state}"};
		try {country = eval("{$country}");} catch(err) {country = "{$country}"};

		var fullAddress = address + ", " + city + ", " + state + ", " + country;
		console.log("xx" + fullAddress);
		
		geocoder_{$id}.geocode( { 'address': fullAddress}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				map_{$id}.setCenter(results[0].geometry.location);
				marker_{$id}.setPosition(results[0].geometry.location);

				{$latHidden}.val(results[0].geometry.location.lat());
				{$lngHidden}.val(results[0].geometry.location.lng());
			}  
		}); 
	}
</script>
